// pages/shippingAddress/list.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    imgPath: "/images",
    isIPhoneX: false,
    //购物车数据
    // listData: [],
    listData: [
    //   {
    //   checked: false,
    //   id: '1',
    //   num: 2,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }, {
    //   checked: false,
    //   id: '2',
    //   num: 1,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }, {
    //   checked: false,
    //   id: '3',
    //   num: 1,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }, {
    //   checked: false,
    //   id: '4',
    //   num: 1,
    //   imgSrc: '/cart/item.jpg',
    //   name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
    //   descrition: '尺寸：L',
    //   price: '138.00'
    // }
  ],
    //选中的标识
    checkIds: [],
    checkedAll: false,
    //总价
    totalPrice: 0,
    //按钮显示
    btnText: '去结算(0)',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;

    const util = require("../../utils/util")
    // this.setData({
    //   imgPath: util.getImgPath()
    // })

    //购物车列表
    /*
    listData: [{
      checked: false,
      id: '1',
      num: 2,
      imgSrc: '/cart/item.jpg',
      name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
      descrition: '尺寸：L',
      price: '138.00'
    }
    */

    //刷新列表
    this.refreshCartList();

    this.getequipment();
  },
  getequipment() {
    let screenHeight = wx.getSystemInfoSync().screenHeight
    let bottom = wx.getSystemInfoSync().safeArea.bottom
    let flag = screenHeight !== bottom
    this.setData({
      isIPhoneX: flag
    })
  },
  refreshCartList() {
    const that = this;

    this.data.listData = [];
    const api = require("../../api/api");
    api.goods.cartList({
      success(res) {
        // console.log("cart,cartList,res", res);
        let rows = res.data.data.rows;
        for (let row of rows) {
        // let num = Number(row.cart_info.spec_stock_id.charAt(row.cart_info.spec_stock_id.length - 1));
         let num = Number(row.cart_info.spec_stock_id.slice(1));
         let bb = row.goods_type_specs[0].childs.findIndex(val => (val.spce_value_id === num))
         let childer = row.goods_type_specs[0].childs[bb]
         let aa = row.goods_type_specs[0]
         let cc = aa.name!='类型'?aa.name:'' 
         let dd = childer?row.goods_type_specs[0].childs[bb].name:''
          that.data.listData.push({
            checked: false,
            id: row.cart_info.cart_id,
            num: row.cart_info.buy_number,
            imgSrc: row.image,
            name: row.goods_name,
            descrition: cc + dd,
            price: row.price,
            goods_id: row.cart_info.goods_id,
            spec_stock_id: row.cart_info.spec_stock_id,
          })
        }

        that.setData({
          listData: that.data.listData,
        })

        // console.log("that.data.listData", that.data.listData)
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onTabbarChange(event) {
    // console.log("onTabbarChange,event", event)
    this.setData({
      active: event.detail
    })
  },
  xianGou() {
    // wx.showToast({
    //   title: '去选购',
    // })
    const util = require("../../utils/util")
        this.setData({
            active: 'home'
          })
    util.setTabbarActive('home');

  },
  itemChecked(e) {
    // console.log("itemChecked", e)
    let id = e.detail.id;
    let checked = e.detail.checked;

    for (let item of this.data.listData) {
      if (item.id == id) {
        item.checked = checked;
      }
    }
    this.setData({
      listData: this.data.listData
    })

    //计算总价
    this.calTotalPrice();
  },
  onNumChange(e) {
    // console.log("onNumChange", e)
    const that = this;
    let id = e.detail.id;
    let num = e.detail.num;

    for (let item of this.data.listData) {
      if (item.id == id) {

        //数值增加
        const api = require("../../api/api")
        if (num > item.num) {
          //增加购物车数量
          api.goods.addCart({
            goods_id: id,
            success(res) {
              // console.log("addCart,res", res)
              if (res.data.code != 0) {
                wx.showToast({
                  title: '增加增物车数量出错',
                  icon: 'none'
                })
                return;
              }

              item.num = res.data.data;
              that.setData({
                listData: that.data.listData
              })
            }
          })
        } else if (num < item.num) {
          //减少购物车数量
          api.goods.delCart({
            goods_id: id,
            success(res) {
              // console.log("delCart,res", res)

              if (res.data.code != 0) {
                wx.showToast({
                  title: '减少增物车数量出错',
                  icon: 'none'
                })
              }

              item.num = res.data.data;
              that.setData({
                listData: that.data.listData
              })
            }
          })
        }
       // this.refreshCartList();
         item.num = num;
        break;
      }
    }
    this.setData({
      listData: this.data.listData
    })

    //计算总价
    this.calTotalPrice();
  },
  /**
   * 全选
   * @param {*} e 
   */
  checkAll(e) {
    this.setData({
      checkedAll: !this.data.checkedAll
    })

    for (let item of this.data.listData) {
      item.checked = this.data.checkedAll;
    }
    this.setData({
      listData: this.data.listData
    })
    // console.log("this.data.listData", this.data.listData)

    this.calTotalPrice();
  },
  /**
   * 计算所有商品价格
   * @returns 选中商品的总价
   */
  calTotalPrice() {
    let totalPrice = 0;
    let count = 0;
    for (let item of this.data.listData) {
      if (item.checked) {
        totalPrice += Number(item.price) * Number(item.num);
        count++;
      }
    }
    this.setData({
      totalPrice: totalPrice.toFixed(2),
      btnText: '去结算(' + count + ')'
    })
    return totalPrice;
  },
  /**
   * 结算
   */
  settle() {
    const that = this;

    let list = [];
    for (const c of this.data.listData) {
      //不选中不处理
      if (!c.checked) continue;

      //选中，待处理
      list.push(c);
    }
    if (list.length <= 0) {
      wx.showToast({
        title: '没有选中商品',
      })
      return;
    }

   // console.log("list", list);
   //  return;

    let goods_info = [];
    for (const c of list) {
      /*
      checked: false,
      id: '1',
      num: 2,
      imgSrc: '/cart/item.jpg',
      name: 'MAGIC DRAGON魔杰龙轻柔倍适学步裤',
      descrition: '尺寸：L',
      price: '138.00'
      */

      //规格
      let spec_stock_id = c.spec_stock_id;

      //图片
      let goodsImages = [c.imgSrc];

      // 商品信息
      goods_info.push({
        //名称
        name: c.name,
        //单价
        price: c.price,
        //图片
        goodsImages: goodsImages,
        //规格
      //  spec: c.specification,
        spec: c.descrition,

        //商品标识
        goods_id: c.goods_id,
        //购买数量
        buy_number: c.num,
        //规格
        spec_stock_id: spec_stock_id
      });
    }

    //价格
    let price = Number(this.data.totalPrice);

    //收货信息
    let receive_info = {
      receive_mobile: '',
      receive_name: '',
      receive_address: ''
    };

    //优惠券标识
    let coupon_id = '';

    //保存订单信息到本地
    let order = {
      //商品信息
      goods_info,
      //总价格
      price,
      //收货信息
      receive_info,
      //优惠券标识
      coupon_id,
      //优惠券名称
      couponName: this.data.couponName,

    }
   
    wx.setStorageSync('order', order);

    let orderReturn = wx.getStorageSync('order');
    // console.log('orderReturn', orderReturn);

    //跳到结算页
    wx.navigateTo({
      url: '/pages/orderSheet/orderSetling?order_from=cart_info',
    })

    // wx.navigateTo({
    //   url: '/pages/orderSheet/paying',
    // })
  },
  /**
   * 删除购物车
   */
  delCart() {
    const that = this;

    const api = require("../../api/api")

    let list = []
    for (let d of this.data.listData) {
      if (d.checked) list.push(d);
    }

    if (list.length <= 0) {
      wx.showToast({
        title: '没有选中商品',
      })
      return;
    }

    wx.showModal({
      title: '删除？',
      content: '删除选定的购物车商品？',
      complete: (res) => {
        //取消
        if (res.cancel) {

        }
        //确定
        if (res.confirm) {
          for (let d of list) {
            api.goods.delCart({
              goods_id: d.id,
              success(resDel) {
                // console.log("delCart,resDel", resDel);

                //刷新列表
                that.refreshCartList();
              }
            })
          }
        }
      }
    })
  }
})